import { createGlobalState } from '@peng_kai/kit/libs/vueuse';
import { i18n, localeManager } from './i18n';

export const useLocale = createGlobalState(() => {
  const localeI18n = i18n.global.locale;
  const localeOptions = Object.entries(localeManager.localeMetas)
    .map(([name, attrs]) => ({ value: name, label: attrs.label, icon: attrs.icon }));
  const localeOption = computed(() => localeOptions.find(option => option.value === localeI18n.value));

  /**
   * 设置区域
   *
   * @param value -要设置的区域设置值
   */
  const setLocale = async (value: string) => {
    if (!localeManager.localesLoaded.includes(value)) {
      const message = await localeManager.loadLocaleMessage(value);

      if (message)
        i18n.global.setLocaleMessage(value, message);
    }

    localeManager.locale = localeI18n.value = value;
  };

  // 从 TG 端获取区域设置
  if (envs.isTgApp) {
    try {
      const tgLocale = localeManager.findMatchingLocale(appValues.language);
      tgLocale && setLocale(tgLocale);
    }
    catch {}
  }

  return { locale: readonly(localeI18n), localeOptions, localeOption, setLocale };
});
